// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
const col = db.collection('userInfo');
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  // 查询该用户在数据库中的记录
  let user = await col.where({
    '_openid': wxContext.OPENID,
  }).get();


  if (user.data.length == 0) {
    let data = {
      '_openid': wxContext.OPENID,
      name: event.name,
      number: event.number,
      address: event.address
    }

    let result = await col.add({
      data: data
    })

    return {
      msg: '添加成功',
      result: result,
    }
  }else{
    let result = await col.where({
      '_openid': wxContext.OPENID,
    }).update({
      data: {
        name: event.name,
        number: event.number,
        address: event.address
      }
    })

    return {
      msg: '更新成功',
      result: result,
    }
  }
}